<?php
namespace addons\jieziarea\model;


use think\Model;

class Jieziarea extends Model
{
    /**
     * @param $level
     * formatted_address 格式化的地址
     * province 省份
     * city 城市
     * district 县区
     * township 村镇
     */
    public function getAddressByQqmap($lat, $lng, $level = 'formatted_address'){
        $address = '';

        if($lng > 0 && $lat > 0 ){
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/?output=json&location=' . $lat . ',' . $lng . '&key=' . config('site.jiezimall_qqmap_key') . '&sig=' . md5('/ws/geocoder/v1/?key=' . config('site.jiezimall_qqmap_key') . '&location=' . $lat . ',' . $lng . '&output=json' . config('site.jiezimall_qqmap_sk'));

            $res = file_get_contents($url, false, stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]));
            $res = json_decode($res, true);//var_dump($res['regeocode']);
//            var_dump($res);
            if(!$res['status']){
//                echo 'formatted_addresses:' . $res['result']['formatted_addresses']['recommend'] . PHP_EOL;
                if($level == 'formatted_address'){
                    $address = $res['result']['formatted_addresses']['recommend'];
                }elseif($level == 'address'){
                    $address = $res['result']['address'];
                }elseif(in_array($level, ['province', 'city', 'district', 'street'])){
                    $address = $res['result']['address_component'][$level];
                }elseif($level == 'code'){
                    $address = [];
                    if($res['result']['ad_info']['adcode']){
                        $address['district_id'] = $res['result']['ad_info']['adcode'];
                        $address['city_id'] = $this->where('id', $address['district_id'])->value('pid');
                        $address['province_id'] = $this->where('id', $address['city_id'])->value('pid');
                    }
                }elseif($level == 'city_name_code'){
                    $address = [];
                    if($res['result']['ad_info']['adcode']){
                        $address = $this->alias('d')
                            ->join('jiezimall_area c', 'd.pid = c.id')
                            ->join('jiezimall_area p', 'c.pid = p.id')
                            ->where('d.id', $res['result']['ad_info']['adcode'])
                            ->field('c.id as city_id, c.name as city_name, d.id as district_id, d.name as district_name, p.id as province_id, p.name as province_name')->find();
                    }
                }
            }
        }
        return $address;
    }
}